const { log } = require('debug');
var express = require('express');
var router = express.Router();
const mysql = require('../DB/db')
const goodTable = require('../services/goods')
const $util = require('../util')

/* GET home page. */
router.get('/', async(req, res, next) => {
    let page = Number(req.query.page) || 1
    let size = Number(req.query.size) || 10
    let status = req.query.status!=0?[Number(req.query.status)]:[1,2]
    let search = req.query.search?(req.query.search!='null'?req.query.search:''):''
    let Res = await goodTable.getGoodList(page,size,status,search)
    res.json({
      code:0,
      ...Res
    })
});


router.get('/info', async(req, res, next) => {
  let returnData = $util.get_check_data(['id'],req)
  if(!returnData.pass){
    // res.status = 500;
    res.json({
      code:1,
      msg:returnData.msg
    })
  }else{
    let Res = await goodTable.getInfo(req.query.id)
    res.json({
      code:0,
      data:Res,
      msg:''
    })
  }
  
});

router.post('/updataInfo', async (req, res, next)=>{
  let returnData = $util.post_check_data(['id'],req)
  if(!returnData.pass){
    res.json({
      code:1,
      msg:returnData.msg
    })
  }else{
    let one = await goodTable.getInfo(req.body.id)
    if(one){
        let where = {
          updated:new Date()
        }
        if(req.body.title){
          where.title = req.body.title
        }
        if(req.body.price){
          where.price = req.body.price
        }
        if(req.body.sell_point){
          where.sell_point = req.body.sell_point
        }
        if(req.body.num){
          where.num = req.body.num
        }
        let Res = await goodTable.updataInfo(where,req.body.id)
        res.json({
          code:0,
          msg:`修改${Res?'成功':'失败'}`
        })

    }else{
      res.json({code:1,msg:'未找到商品'})
    }
  }
})

router.post('/updataOne', async(req,res,next)=>{
    let returnData = $util.post_check_data(['id','status'],req)
    if(!returnData.pass){
      res.json({
        code:1,
        msg:returnData.msg
      })
    }else{
      let one = await goodTable.getInfo(req.body.id)
      if(one){
        let where = {
          status:req.body.status,
          updated:new Date()
        }
        let Res = await goodTable.updataInfo(where,req.body.id)
        res.json({
          code:0,
          msg:`修改${Res?'成功':'失败'}`
        })
      }else{
        res.json({code:1,msg:'未找到商品'})
      }
    }
})



module.exports = router;
